#!/bin/bash

if [ $# != 5 ];then

    echo "错误："
    echo "  a.请指定私有镜像仓库的 IP 和 端口 ！！！"
    echo "  b.请指定私有镜像仓库的 账号 和 密码 ！！！"
    echo "处理："
    echo "  然后如下格式重新执行："
    echo "    ./server_install.sh \"k3s.harbor.com\" 5050 \"zhangsan\" \"123456\" \"mysql://root:123456@tcp(192.168.181.126:3306)/k3s\""
    exit 1
fi

if [ ! -d "/var/lib/rancher/k3s/agent/images" ]; then
	mkdir -p /var/lib/rancher/k3s/agent/images
fi

if [ ! -d "/etc/rancher/k3s" ]; then
	mkdir -p /etc/rancher/k3s
fi

dnum=0
if [[ -z `yum list installed | grep selinux-policy-minimum` ]] ; then
    (( dnum ++))
    echo "K3S需要操作系统底层组件：selinux-policy-minimum 支持，请手工安装！"
    echo "   请搭建本地yum源或在线安装，执行：yum install -y selinux-policy-minimum"
fi

if [[ -z `yum list installed | grep selinux-policy-targeted` ]] ; then
    (( dnum ++))
    echo "K3S需要操作系统底层组件：selinux-policy-targeted 支持，请手工安装！"
    echo "   请搭建本地yum源或在线安装，执行：yum install -y selinux-policy-targeted"
fi

if [[ -z `yum list installed | grep container-selinux` ]] ; then
    (( dnum ++))
    echo "K3S需要操作系统底层组件：container-selinux 支持，请手工安装! "
    echo "   请搭建本地yum源或在线安装，执行：yum install -y container-selinux"
fi

if [[ $dnum -gt 0 ]] ; then
    exit 1
fi

if [[ -z `yum list installed | grep k3s-selinux` ]] ; then
    yum install -y ./shell/k3s-selinux-0.2-1.el7_8.noarch.rpm
fi

scp ../image/k3s-airgap-images-amd64.tar /var/lib/rancher/k3s/agent/images/k3s-airgap-images-amd64.tar

export INSTALL_K3S_SKIP_DOWNLOAD=true

export INSTALL_K3S_EXEC="server --datastore-endpoint=$5"

cd ./shell
cp k3s /usr/local/bin
cp registries.yaml /etc/rancher/k3s/registries.yaml
sed -i "s/ip/$1/g" /etc/rancher/k3s/registries.yaml
sed -i "s/port/$2/g" /etc/rancher/k3s/registries.yaml
sed -i "s/userne/$3/g" /etc/rancher/k3s/registries.yaml
sed -i "s/passwd/$4/g" /etc/rancher/k3s/registries.yaml
chmod u+x /usr/local/bin/k3s
./install.sh
